﻿using Lg.Core.Exceptions;
using Microsoft.EntityFrameworkCore;
using Survey.Models;
using System.Text.RegularExpressions;
using TemplateEngine;
using static QRCoder.PayloadGenerator;

namespace Survey.Core
{
    public class TemplateServer(IDbContextFactory<SurveyDbContext> dbContextFactory)
    {

        readonly IDbContextFactory<SurveyDbContext> _dbContextFactory = dbContextFactory;
        public  async Task<TemplateManager> GetTemplate(string url)
        {
            return await Task.Run(async () =>
            {
                using var dbContext = _dbContextFactory.CreateDbContext();
                var template = dbContext.Template.FirstOrDefault(x => x.IsDelete == 0 && x.Url.ToLower().Equals(url.ToLower()));
                if (template != null&&template.Text!=null)
                {
                    string? text=await FormatTpl(template.Text);
                    return TemplateManager.FromString(text??throw new LgException("模版内容不存在！"));
                }
                else
                {
                    throw new LgException("模版不存在！");
                }

            });
        }

        public async Task<string?> FormatTpl(string? tpl)
        {
            return await Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(tpl))
                {
                    Regex r = new Regex("<lgcms data=\"(.+)\" />");
                    MatchCollection mc = r.Matches(tpl);
                    if (mc.Count > 0)
                    {
                        using var dbContext = _dbContextFactory.CreateDbContext();
                        for (int i = 0; i < mc.Count; i++)
                        {
                            int id = Convert.ToInt16(Regex.Replace(mc[i].Value, "<lgcms data=\"(.+)\" />", "$1"));
                            var template = dbContext.Template.FirstOrDefault(x => x.IsDelete == 0 && x.Id == id);
                            if (template != null)
                            {
                                tpl = tpl.Replace(mc[i].Value, template.Text);
                            }
                        }
                    }
                }
                return tpl;
            });
            
        }
    }
}
